import React, {useEffect} from 'react';
import Grid from "@material-ui/core/Grid";
import {CircularProgress, Collapse, Fab, Typography} from "@material-ui/core";
import {useDispatch, useSelector} from "react-redux";
import {
  getActionOnActivities,
  getActivityTypes,
  getAllPlatforms,
  resetFilterData,
  selectActivityTypes,
  selectDeselectActionOnActivities,
  selectPlatform
} from "../../../../../../redux/reducers/editor";
import {makeStyles} from "@material-ui/core/styles";
import RefreshIcon from '@material-ui/icons/Refresh';
import {
  setConnectionErrorActionOnActivity,
  setConnectionErrorActivityType,
  setConnectionErrorPlatform
} from "../../../../../../redux/reducers/errorMessages";
import {scrollToTop} from "../../../../../../assets/functions/functions";
import Button from "@material-ui/core/Button";
import MenuMultiSelect from "../../../Common/MenuMultiSelect/MenuMultiSelect";
import {getActiveGoals} from "../../../../../../redux/reducers/gqiEditor";

const useStyles = makeStyles((theme) => ({
  gutterBottom: {
    marginBottom: theme.spacing(2)
  },
  gutterRight: {
    marginRight: theme.spacing(1),
  }
}));

export default function Datasets({handleStepForward}) {
  // Local constants
  const dispatch = useDispatch();
  const styles = useStyles();

  const platformsData = useSelector(state => state.editor.fetchedData.platforms);
  const activityTypesData = useSelector(state => state.editor.fetchedData.activityTypes);
  const actionOnActivitiesData = useSelector(state => state.editor.fetchedData.actionOnActivities);
  const selectedPlatform = useSelector(state => state.editor.selectedData.platforms);
  const selectedActivityTypes = useSelector(state => state.editor.selectedData.activityTypes);
  const selectedActionOnActivities = useSelector(state => state.editor.selectedData.actionOnActivities);
  const selectedActivityName = useSelector(state => state.editor.selectedData.activityName);

  const errorPlatform = useSelector(state => state.errorMessages.connectionErrors.platform);
  const errorActivityType = useSelector(state => state.errorMessages.connectionErrors.activityType);
  const errorActionOnActivity = useSelector(state => state.errorMessages.connectionErrors.actionOnActivity);

  useEffect(() => {
    scrollToTop();
    dispatch(getAllPlatforms());
  }, []);

  const handleRefresh = (type) => () => {
    if (type === "platform") {
      dispatch(setConnectionErrorPlatform(false));
      dispatch(getAllPlatforms());
    }
    if (type === "activityType") {
      dispatch(setConnectionErrorActivityType(false));
      dispatch(getActivityTypes(selectedPlatform));
    }
    if (type === "actionOnActivities") {
      dispatch(setConnectionErrorActionOnActivity(false));
      dispatch(getActionOnActivities(selectedPlatform, selectedActivityTypes));
    }
  }

  // Platform
  const handleSelectPlatform = (event, values) => {
    dispatch(selectPlatform(values));
    if (values.length !== 0)
      dispatch(getActivityTypes(values));
  };

  // TODO: Fixing these selecting all functions
  const handleSelectAllPlatform = (e) => {
    console.log(e)
    dispatch(selectPlatform(platformsData));
    dispatch(getActivityTypes(platformsData));
    if (selectedActivityTypes.length !== 0)
      dispatch(selectActivityTypes([]));
  }

  // Activity Types
  const handleSelectActivityType = (event, values) => {
    dispatch(selectActivityTypes(values));
    if (values.length !== 0)
      dispatch(getActionOnActivities(selectedPlatform, values));
  };

  const handleSelectAllActivityTypes = () => {
    dispatch(selectActivityTypes(activityTypesData));
    dispatch(getActionOnActivities(selectedPlatform, activityTypesData));
  }

  // Action on Activities
  const handleSelectActionOnActivity = (event, values) => {
    dispatch(selectDeselectActionOnActivities(values));
  };

  const handleSelectAllActionOnActivities = () => {
    dispatch(selectDeselectActionOnActivities(actionOnActivitiesData));
    if (selectedActivityName.length !== 0)
      dispatch(resetFilterData());
  }


  return (
    <>
      <Grid container md={9} lg={8} xl={6}>

        <Grid container direction="column">
          {platformsData.length === 0 ?
            <Grid container direction="column" alignItems="center">
              <CircularProgress className={styles.gutterBottom}/>
              <Typography variant="overline"> Loading platform data </Typography>
            </Grid>
            : !errorPlatform ?
              <Grid item xs className={styles.gutterBottom}>
                <MenuMultiSelect
                  name={"Platforms"}
                  dataSource={platformsData}
                  itemName={selectedPlatform}
                  selectAll={handleSelectAllPlatform}
                  handleChange={handleSelectPlatform}
                />
              </Grid>
              :
              <Grid container justify="center" alignItems="center">
                <Fab color="primary" size="small" className={styles.gutterRight}
                     onClick={handleRefresh("platform")}>
                  <RefreshIcon/>
                </Fab>
                <Grid item>
                  <Typography> Connection problem, please retry </Typography>
                </Grid>
              </Grid>
          }

          <Collapse in={selectedPlatform.length !== 0}>
            {activityTypesData.length === 0 ?
              <Grid container direction="column" alignItems="center">
                <CircularProgress className={styles.gutterBottom}/>
                <Typography variant="overline"> Loading activity types data </Typography>
              </Grid>
              : !errorActivityType ?
                <Grid item xs className={styles.gutterBottom}>
                  <MenuMultiSelect
                    name={"Activity types"}
                    dataSource={activityTypesData}
                    itemName={selectedActivityTypes}
                    selectAll={handleSelectAllActivityTypes}
                    handleChange={handleSelectActivityType}
                  />
                </Grid>
                :
                <Grid container justify="center" alignItems="center">
                  <Fab color="primary" size="small" className={styles.gutterRight}
                       onClick={handleRefresh("activityType")}>
                    <RefreshIcon/>
                  </Fab>
                  <Grid item>
                    <Typography>Connection problem, please retry</Typography>
                  </Grid>
                </Grid>}
          </Collapse>

          <Collapse in={selectedActivityTypes.length !== 0}>
            {actionOnActivitiesData.length === 0 ?
              <Grid container direction="column" alignItems="center">
                <CircularProgress className={styles.gutterBottom}/>
                <Typography variant="overline"> Loading action on activities data </Typography>
              </Grid>
              : !errorActionOnActivity ?
                <Grid item xs className={styles.gutterBottom}>
                  <MenuMultiSelect
                    name={"Action on Activities"}
                    dataSource={actionOnActivitiesData}
                    itemName={selectedActionOnActivities}
                    selectAll={handleSelectAllActionOnActivities}
                    handleChange={handleSelectActionOnActivity}
                  />
                </Grid>
                :
                <Grid container justify="center" alignItems="center">
                  <Fab color="primary" size="small" className={styles.gutterRight}
                       onClick={() => handleRefresh("actionOnActivities")}>
                    <RefreshIcon/>
                  </Fab>
                  <Grid item>
                    <Typography> Connection problem, please retry </Typography>
                  </Grid>
                </Grid>
            }
          </Collapse>
        </Grid>

        <Button
          variant="contained" color="primary" onClick={handleStepForward}
          disabled={!(selectedPlatform.length !== 0 && selectedActivityTypes.length !== 0
            && selectedActionOnActivities.length !== 0)}>
          Next
        </Button>

      </Grid>
    </>
  )
};
